<template>
  <div class="user_Container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 添加用户 -->
      <el-row type="flex" justify="space-between">
        <el-col :span="6">
          <el-input
            placeholder="输入关键字搜索用户"
            prefix-icon="el-icon-search"
            clearable
            v-model="userParams.query"
            @clear="getUserList"
          >
            <el-button class="el-icon-search user_search" slot="append" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <div class="grid-content bg-purple-light">
            <el-button type="primary" @click="dialogFormVisible=true ">添加用户</el-button>
          </div>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="userList" style="width: 100%; height:260px" border stripe>
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="role_name" label="身份"></el-table-column>
        <!-- 使用作用域插槽 -->
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange($event,scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="mg_state" label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-tooltip class="item" effect="dark" content="编辑" placement="top" :enterable="false">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="editUser(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="deleteUser(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="editRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userParams.pagenum"
        :page-sizes="[4]"
        :page-size="userParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogFormVisible"
      width="30%"
      :show-close="false"
      :modal="true"
      :close-on-click-modal="false"
    >
      <el-form :model="newUser" :rules="newUserRules" ref="newUserFormRef">
        <el-form-item label="用户名" label-width="20%" prop="username">
          <el-input v-model="newUser.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="20%" prop="password">
          <el-input v-model="newUser.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" label-width="20%" prop="password2">
          <el-input v-model="newUser.password2" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="20%" prop="email">
          <el-input v-model="newUser.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" label-width="20%" prop="mobile">
          <el-input v-model="newUser.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUserCancel">取 消</el-button>
        <el-button type="primary" @click="admitNewUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 角色分配对话框 -->
    <el-dialog title="提示" :visible.sync="editRoleFormVisible" width="30%">
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>
          切换角色
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义密码规则
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value !== this.newUser.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    // 自定义手机号规则
    var validateMobile = (rule, value, callback) => {
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error('手机号格式有误'))
      } else {
        callback()
      }
    }
    // 自定义邮箱规则/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
    var validateEmail = (rule, value, callback) => {
      if (
        !/^([a-zA-Z0-9]+[_|-|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|-|.]?)*[a-zA-Z0-9]+.[a-zA-Z]{2,3}$/.test(
          value
        )
      ) {
        callback(new Error('邮箱格式有误'))
      } else {
        callback()
      }
    }
    return {
      // 给服务器传递的获取用户参数
      userParams: {
        query: '',
        pagenum: 1,
        pagesize: 4
      },
      total: 0,
      //用户列表
      userList: [],
      // 控制添加用户对话框的显示与隐藏
      dialogFormVisible: false,
      editId: '',
      editRoleFormVisible: false,
      // 当前的角色详情暂存
      userInfo: '',
      // 所有的角色信息
      roleList: [],
      // 目前选中的角色id
      selectedRoleId: '',
      // 新用户的暂存数据
      newUser: {
        username: '',
        mobile: '',
        password: '',
        email: '',
        password2: ''
      },
      newUserRules: {
        username: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 10,
            message: '长度在 6 到 10 个字符之间',
            trigger: 'blur'
          }
        ],
        password2: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 10,
            message: '长度在 6 到 10 个字符之间',
            trigger: 'blur'
          },
          {
            validator: validatePass2,
            message: '两次输入不一致',
            trigger: 'blur'
          }
        ],
        email: [
          {
            validator: validateEmail,
            message: '邮箱格式有误',
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            validator: validateMobile,
            message: '手机号格式有误',
            trigger: 'blur'
          }
        ]
      }
    }
  },

  created() {
    this.getUserList()
  },
  methods: {
    // 获取当前用户列表
    getUserList() {
      this.$http
        .get('users', {
          params: this.userParams
        })
        .then(res => {
          // console.log(res.data)
          if (res.data.meta.status != 200) {
            console.log('获取用户列表失败')
          }
          this.userList = [...res.data.data.users]
          this.total = res.data.data.total
        })
      // console.log(this.userList)
    },
    // 监听每一页呈现数据的变化
    handleSizeChange(nowPageSize) {
      this.userParams.pagesize = nowPageSize
      this.getUserList()
    },
    // 监听页码改变
    handleCurrentChange(nowPage) {
      this.userParams.pagenum = nowPage
      // this.getUserList()
      this.getUserList()
    },
    // 监听用户状态的改变，只需要传递row就可以了,users/{:uId}/state/:type
    userStateChange(val, userInfo) {
      this.$http
        .put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
        .then(res => {
          if (res.data.meta.status != 200) {
            this.$message.closeAll()
            this.$message.error('更新用户权限失败')
            userInfo.mg_state = !userInfo.mg_state
            return
          }
          // console.log(res.data)
          this.$message.closeAll()
          this.$message.success('修改用户权限成功')
        })
    },
    // 取消添加用户
    addUserCancel() {
      this.dialogFormVisible = false
      this.$refs.newUserFormRef.resetFields()
    },
    // 添加新用户，如果是编辑操作，还需要删除旧用户
    admitNewUser() {
      this.$refs.newUserFormRef.validate(valid => {
        if (!valid) {
          this.$message.closeAll()
          this.$message.error('请检查表单信息')
        } else {
          this.$http.post('users', this.newUser).then(res => {
            console.log(res.data)

            if (res.data.meta.status != 201) {
              this.$message.error('请重试')
            } else {
              this.$message.success('成功！')
              this.dialogFormVisible = false
            }
          })
        }
      })
      //编辑操作判断
      if (this.editId) {
        //删除此用户
        this.$http.delete(`users/${this.editId}`).then(res => {
          if (res.data.meta.status != 200) {
            this.$message.error('错误，请暂停使用并联系维护人员')
          }
          this.$message.success('成功')
        })
        this.editId = ''
      }
      this.$router.go(0)
    },
    // 编辑现有用户
    editUser(userData) {
      Object.keys(this.newUser).forEach(key => {
        this.newUser[key] = userData[key]
      })
      // console.log(this.newUser)
      this.editId = userData.id
      this.dialogFormVisible = true
    },
    // 删除用户
    deleteUser(userData) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.editId = userData.id
          this.$http.delete(`users/${this.editId}`).then(res => {
            if (res.data.meta.status != 200) {
              this.$message.closeAll()
              this.$message.error('删除失败')
            }
            this.$message.success('删除成功')
          })
          this.editId = ''
          this.$router.go(0)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 角色分配
    editRole(userInfo) {
      this.userInfo = userInfo
      this.getRoleList()
      // console.log(userInfo)
      this.editRoleFormVisible = true
    },
    // 获取所有的角色列表
    getRoleList() {
      this.$http.get('roles').then(res => {
        if (res.data.meta.status != 200) {
          return this.$message.error('获取角色列表失败')
        }
        this.roleList = res.data.data
      })
    },
    // 新角色保存
    saveRoleInfo() {
      if (!this.selectedRoleId) {
        this.$message.closeAll()
        return this.$message.error('请选择一个新的角色')
      }
      this.$http
        .put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
        .then(res => {
          if (res.data.meta.status != 200) {
            this.$message.closeAll()
            return this.$message.error('失败')
          }
          this.$message.success('设置角色成功')
          this.$router.go(0)
        })
    }
  }
}
</script>

<style lang="less" scoped>
.user_Container {
  height: 100%;
  .el-card {
    margin-top: 20px;
    .user_search:hover {
      color: white;
      background-color: #409eff;
    }
    .el-pagination {
      margin-top: 15px;
    }
  }
  .el-table {
    margin-top: 15px;
  }
}
</style>